package com.opentool.util;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import org.apache.commons.lang3.StringUtils;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
public class IpUtil {

	public static String udpRemoteAddress(DatagramPacket datagramPacket){
		InetSocketAddress  remoteAddress = datagramPacket.sender();
		String ip = remoteAddress.getAddress().getHostAddress();
		int port = remoteAddress.getPort();
		return String.format("%s:%s",ip,port);
	}
	public static String udpRemoteIp(DatagramPacket datagramPacket){
		InetSocketAddress  remoteAddress = datagramPacket.sender();
		String ip = remoteAddress.getAddress().getHostAddress();
		return ip;
	}

	 public static String getRemoteAddress(ChannelHandlerContext ctx){
		   SocketAddress socketAddress = ctx.channel().remoteAddress();
		   if(socketAddress!=null){
		   		return socketAddress.toString();
		   }
		   return "0.0.0.0";
	 }
	public static String getRemoteIpAddr(ChannelHandlerContext ctx){
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
		String clientIP = insocket.getAddress().getHostAddress();
		return clientIP;
	}

	public static String bytesToIp(byte[] bytes) {
		return (bytes[0] & 0xFF) + "." + (bytes[1] & 0xFF) + "." + (bytes[2] & 0xFF) + "." + (bytes[3] & 0xFF);
	}

	public static byte[] ipToHex(String ipAdd){
		byte[] binIP = new byte[4];
		String[] strs = ipAdd.split("\\.");
		for(int i=0;i<strs.length;i++){
			binIP[i] = (byte) Integer.parseInt(strs[i]);
		}
		return binIP;
	}

	public static String getLocalIpAddr(){
		String localIpAddr= StringUtils.EMPTY;
		try{
			InetAddress addr = InetAddress.getLocalHost();
			System.out.println("IP地址：" + addr.getHostAddress() + "，主机名：" + addr.getHostName());
			localIpAddr=addr.getHostAddress();
		}catch (Exception e){
			e.printStackTrace();
			System.err.println("获取本地IP地址失败");
		}
		return localIpAddr;
	}
}
